﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Text;
using System.Web.Services;

using CE.Database;
using CE.Mail;
using CE.Global;
using CE.CarInsurance;
using CE.User;
using CE.Security;

public partial class car_insurance_proposal_form : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[General.UserId] == null || Session[General.CarId] == null)
        {
            Response.Redirect("car-quote.aspx");
        }
        if (!IsPostBack)
        {
            LoadTitles();
            txtUserName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtUserName.ClientID + "','" + rfvUserName.ClientID + "','" + revUserName.ClientID + "');DefaultName(this, event);");
            txtUserName.Attributes.Add("onfocus", "ClearText(this, event);");
            txtUserEmail.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtUserEmail.ClientID + "','" + rfvUserEmail.ClientID + "','" + revUserEmail.ClientID + "');DefaultEmail(this, event);");
            txtUserEmail.Attributes.Add("onfocus", "ClearText(this, event);");
            txtUserMobile.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtUserMobile.ClientID + "','" + rfvUserMobile.ClientID + "','" + revUserMobile.ClientID + "');DefaultPhone(this, event);");
            txtUserMobile.Attributes.Add("onfocus", "ClearText(this, event);");

            HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
            if (_cookie != null)
            {
                txtUserEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                txtUserName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtUserMobile.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                string _isaccept = "FALSE";
                string[] _CK = _cookie.Value.Split('&');
                if (_CK.Length > 3)
                {
                    _isaccept = MySecurity.Decrypt(_cookie.Values.Get("IsAccept"), true);
                    if (_isaccept != null && _isaccept == "TRUE")
                    {
                        hdnIsAceept.Value = "TRUE";
                    }
                }
            }
            divAgreement.Style.Add("display", "");
            if (hdnIsAceept.Value == "TRUE")
            {
                txtIsAccept.Text = "1";
                chkAggrement.Checked = true;
                divAgreement.Style.Add("display", "none");
            }
            if (Request.QueryString["qid"] != null && Request.QueryString["qid"].ToString() != string.Empty)
            {
                hdnQuoteId.Value = Request.QueryString["qid"].ToString();
            }
            if (Request.QueryString["cid"] != null && Request.QueryString["cid"].ToString() != string.Empty)
            {
                hdnCarId.Value = Request.QueryString["cid"].ToString();
            }
            if (Request.QueryString["pid"] != null && Request.QueryString["pid"].ToString() != string.Empty)
            {
                hdnPolicyId.Value = Request.QueryString["pid"].ToString();
            }
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("results.aspx?type=email&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("proposal");
            Page.Validate("proposal");
            if (Page.IsValid)
            {
                #region Remove DOB on 28 Nov 2014
                //int _day = Convert.ToInt32(ddlDay.Text);
                //int _month = Convert.ToInt32(ddlMonth.Text);
                //int _year = Convert.ToInt32(ddlYear.Text);
                //if (!ValidDate(_year, _month, _day))
                //{
                //    lblErrorMessage.Text = "Please select valid DOB";
                //    return;
                //}
                #endregion

                Int64 _userId = 0;
                Int64 _carId = 0;
                Int64 _carResultId = 0;
                Int64 _ProviderId = 0;
                Int64 _ExistingUserId = 0;
                string ExistingEmail = "";
                if (Session[General.UserEmail] != null && Session[General.UserEmail].ToString() != string.Empty)
                {
                    ExistingEmail = Session[General.UserEmail].ToString();
                }
                if (Session[CE.Global.General.UserId] != null)
                {
                    if (!Int64.TryParse(Session[General.UserId].ToString(), out _ExistingUserId))
                    {
                        _ExistingUserId = 0;
                    }
                }
                if (Session[General.CarId] != null)
                {
                    if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                    {
                        _carId = 0;
                    }
                }

                #region Customer Details
                Account _useraccount = new Account();
                AccountDB _useraccountdb = new AccountDB();

                _useraccount = _useraccountdb.GetUserAccount(EmailAddress, 400);
                if (_useraccount != null && _useraccount.CEID > 0)
                {
                    _userId = _useraccount.CEID;
                    Profile _userprofile = new Profile();
                    ProfileDB _userprofiledb = new ProfileDB();

                    Contact _usercontact = new Contact();
                    ContactDB _usercontactdb = new ContactDB();

                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);

                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        _userprofile.SurName = string.Empty;
                        _userprofile.FirstName = Server.HtmlEncode(txtUserName.Text);
                        _userprofile.IsAcceptTC = true;
                        _userprofiledb.Insert(_userprofile);
                    }
                    _usercontact = _usercontactdb.GetContact(_useraccount.CEID);
                    if (_usercontact != null && _usercontact.ContactId > 0)
                    {
                        _usercontact.Mobile = txtUserMobile.Text.Trim();
                        _usercontactdb.Insert(_usercontact);
                    }
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserName] = _userprofile.FirstName;
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_userprofile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    Session[CE.Global.General.UserPhoneNo] = _usercontact.Mobile;
                    _useraccount = null;
                    _useraccountdb = null;
                    _userprofile = null;
                    _userprofiledb = null;
                    _usercontact = null;
                    _usercontactdb = null;
                    if (_ExistingUserId != _userId)
                    {
                        UpdateUserIdCarDetails(_carId, _userId, _ExistingUserId, ExistingEmail, "SWITCH", txtUserEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtUserMobile.Text.Trim());
                    }
                }
                else
                {
                    //General.ClearAllSession(this.Page, "USER");
                    UpdateProfile(_userId, _carId);
                    if (Session[CE.Global.General.UserId] != null)
                    {
                        if (!Int64.TryParse(Session[CE.Global.General.UserId].ToString(), out _userId))
                        {
                            _userId = 0;
                        }
                    }
                    UpdateUserIdCarDetails(_carId, _userId, _ExistingUserId, ExistingEmail, "SWITCH", txtUserEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtUserMobile.Text.Trim());
                    SendMailToUser(txtUserEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtUserMobile.Text.Trim());
                }
                SetCookies();
                #endregion

                if (Session[General.UserId] != null)
                {
                    if (!Int64.TryParse(Session[General.UserId].ToString(), out _userId))
                    {
                        _userId = 0;
                    }
                }
                if (Session[General.CarId] != null)
                {
                    if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                    {
                        _carId = 0;
                    }
                }

                if (Request.QueryString["rid"] != null && Request.QueryString["rid"].ToString() != string.Empty)
                {
                    if (!Int64.TryParse(Request.QueryString["rid"].ToString(), out _carResultId))
                    {
                        _carResultId = 0;
                    }
                }

                if (Request.QueryString["prid"] != null && Request.QueryString["prid"].ToString() != string.Empty)
                {
                    if (!Int64.TryParse(Request.QueryString["prid"].ToString(), out _ProviderId))
                    {
                        _ProviderId = 0;
                    }
                }

                if (_userId > 0 && _carId > 0 && _carResultId > 0 && _ProviderId > 0)
                {
                    Int64 ProposalId = 0;
                    string _strPaymentType = ddlPaymentType.Text;
                    string strEmail = Server.HtmlEncode(txtUserEmail.Text.Trim());
                    string strName = Server.HtmlEncode(txtUserName.Text.Trim());
                    string strMobile = Server.HtmlEncode(txtUserMobile.Text.Trim());
                    DateTime _dtDOB = new DateTime();//Remove DOB on 28 Nov 2014 - new DateTime(_year, _month, _day);

                    ProposalId = SaveSelectedResult(_userId, _carId, _carResultId, _ProviderId, strEmail.ToString(), strName.ToString(), strMobile.ToString(), _dtDOB, _strPaymentType);
                    SendProposalToUserNEW(_carResultId.ToString(), _ProviderId);
                    if (NotificationEmail(_carResultId.ToString(), strEmail.ToString(), strName.ToString(), strMobile.ToString()))
                    {
                        Int64 Update = 0;
                        MyDatabase _dbUpdate = new MyDatabase();
                        string _spName = "sprocMobileProposalInsertUpdateSingleItem";

                        SortedList _spList = new SortedList();
                        _spList.Add("@ProposalId", ProposalId);
                        _spList.Add("@Step", 2);

                        object _retObjectUserIdUpdate = _dbUpdate.ExecuteSP(_spName, _spList);
                        Update = Convert.ToInt64(_retObjectUserIdUpdate);
                        if (Update > 0)
                        {
                            CE.Global.General.ClearAllSession(this.Page, "CI");
                            Response.Redirect("thankyou.aspx?type=email&resultid=" + _carResultId + "&email=1");
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void LoadTitles()
    {
        lblApplicationTitle.Text = Resources.CarMenu.SubmitOrder;
        //lblDOB.Text = Resources.CarMenu.SelectDOB;
        //lblPaymentType.Text = Resources.CarMenu.PaymentType;
        btnSubmit.Text = Resources.CarMenu.BuyNow;
        //ibtnBack.ImageUrl = Resources.CarMenu.ButtonBackUrl;
        lblAggrement.Text = Resources.UserMessage.Aggrement;
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtUserName.Text = HttpUtility.HtmlEncode(txtUserName.Text.Trim());
        txtUserEmail.Text = HttpUtility.HtmlEncode(txtUserEmail.Text);
        txtUserMobile.Text = HttpUtility.HtmlEncode(txtUserMobile.Text);

        //PaymentType
        if (rfvPaymentType.Enabled && rfvPaymentType.ValidationGroup == strValidationGroup)
        {
            rfvPaymentType.Validate();
            if (rfvPaymentType.IsValid == false)
            {
                ddlPaymentType.ControlStyle.CssClass = "dropdown-fields validationError";
            }
            else
            {
                ddlPaymentType.ControlStyle.CssClass = "dropdown-fields";
            }
        }
        else
        {
            ddlPaymentType.ControlStyle.CssClass = "dropdown-fields";
        }

        #region user
        //Name
        if (rfvUserName.Enabled && rfvUserName.ValidationGroup == strValidationGroup)
        {
            rfvUserName.Validate();
            if (rfvUserName.IsValid == false)
            {
                txtUserName.ControlStyle.CssClass = "your-detail-fields validationError";
            }
            else
            {
                txtUserName.ControlStyle.CssClass = "your-detail-fields-1";
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "your-detail-fields-1";
        }

        if (revUserName.Enabled && revUserName.ValidationGroup == strValidationGroup)
        {
            if (rfvUserName.IsValid)
            {
                revUserName.Validate();
                if (revUserName.IsValid == false)
                {
                    txtUserName.ControlStyle.CssClass = "your-detail-fields validationError";
                }
                else
                {
                    txtUserName.ControlStyle.CssClass = "your-detail-fields-1";
                }
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "your-detail-fields-1";
        }

        //Email
        if (rfvUserEmail.Enabled && rfvUserEmail.ValidationGroup == strValidationGroup)
        {
            rfvUserEmail.Validate();
            if (rfvUserEmail.IsValid == false)
            {
                txtUserEmail.ControlStyle.CssClass = "your-detail-fields validationError";
            }
            else
            {
                txtUserEmail.ControlStyle.CssClass = "your-detail-fields-1";
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "your-detail-fields-1";
        }

        if (revUserEmail.Enabled && revUserEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvUserEmail.IsValid)
            {
                revUserEmail.Validate();
                if (revUserEmail.IsValid == false)
                {
                    txtUserEmail.ControlStyle.CssClass = "your-detail-fields validationError";
                }
                else
                {
                    txtUserEmail.ControlStyle.CssClass = "your-detail-fields-1";
                }
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "your-detail-fields-1";
        }

        //Mobile No
        if (rfvUserMobile.Enabled && rfvUserMobile.ValidationGroup == strValidationGroup)
        {
            rfvUserMobile.Validate();
            if (rfvUserMobile.IsValid == false)
            {
                txtUserMobile.ControlStyle.CssClass = "your-detail-fields validationError";
            }
            else
            {
                txtUserMobile.ControlStyle.CssClass = "your-detail-fields-1";
            }
        }
        else
        {
            txtUserMobile.ControlStyle.CssClass = "your-detail-fields-1";
        }

        if (revUserMobile.Enabled && revUserMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvUserMobile.IsValid)
            {
                revUserMobile.Validate();
                if (revUserMobile.IsValid == false)
                {
                    txtUserMobile.ControlStyle.CssClass = "your-detail-fields validationError";
                }
                else
                {
                    txtUserMobile.ControlStyle.CssClass = "your-detail-fields-1";
                }
            }
        }
        else
        {
            txtUserMobile.ControlStyle.CssClass = "your-detail-fields-1";
        }
        #endregion
    }

    private Int64 SaveSelectedResult(Int64 UserId, Int64 CarId, Int64 CarResultId, Int64 ProviderCompanyId, string Email, string Name, string Mobile, DateTime DOB, string PaymentType)
    {
        try
        {
            float _AnnualPremium = 0.0f;
            float _PromotionPrice = 0.0f;
            float _TotalVMI = 0.0f;
            float _TotalCMI = 0.0f;
            MyDatabase _db = new MyDatabase();
            System.Data.DataTable _dtSeletectItem = new System.Data.DataTable("SelectedResultItem");
            _dtSeletectItem = _db.GetDataTable("SELECT TOP 1 * FROM tblCarInsuranceTempResultTH WHERE CarId = " + CarId.ToString() + " AND CITempResultId = " + CarResultId.ToString());
            if (_dtSeletectItem != null && _dtSeletectItem.Rows.Count > 0)
            {
                if (_dtSeletectItem.Rows[0]["AnnualPremium"] != null && _dtSeletectItem.Rows[0]["AnnualPremium"].ToString() != string.Empty)
                {
                    if (!float.TryParse(_dtSeletectItem.Rows[0]["AnnualPremium"].ToString(), out _AnnualPremium))
                    {
                        _AnnualPremium = 0.0f;
                    }
                }
                if (_dtSeletectItem.Rows[0]["PromotionPrice"] != null && _dtSeletectItem.Rows[0]["PromotionPrice"].ToString() != string.Empty)
                {
                    if (!float.TryParse(_dtSeletectItem.Rows[0]["PromotionPrice"].ToString(), out _PromotionPrice))
                    {
                        _PromotionPrice = 0.0f;
                    }
                }
                if (_dtSeletectItem.Rows[0]["TotalVMI"] != null && _dtSeletectItem.Rows[0]["TotalVMI"].ToString() != string.Empty)
                {
                    if (!float.TryParse(_dtSeletectItem.Rows[0]["TotalVMI"].ToString(), out _TotalVMI))
                    {
                        _TotalVMI = 0.0f;
                    }
                }
                if (_dtSeletectItem.Rows[0]["TotalCMI"] != null && _dtSeletectItem.Rows[0]["TotalCMI"].ToString() != string.Empty)
                {
                    if (!float.TryParse(_dtSeletectItem.Rows[0]["TotalCMI"].ToString(), out _TotalCMI))
                    {
                        _TotalCMI = 0.0f;
                    }
                }
            }
            _db = null;
            Int64 Update = 0;
            MyDatabase _dbUpdate = new MyDatabase();
            string _spName = "sprocMobileProposalInsertUpdateSingleItem";

            SortedList _spList = new SortedList();
            _spList.Add("@ProposalId", 0);
            _spList.Add("@RefCEUserId", UserId);
            _spList.Add("@CarId", CarId);
            _spList.Add("@CarResultId", CarResultId);
            _spList.Add("@ProviderCompanyId", ProviderCompanyId);
            _spList.Add("@Email", Email);
            _spList.Add("@Name", Name);
            _spList.Add("@Mobile", Mobile);
            //_spList.Add("@DOB", DOB); //Remove DOB on 28 Nov 2014
            _spList.Add("@AnnualPremium", _AnnualPremium);
            _spList.Add("@PromotionPrice", _PromotionPrice);
            _spList.Add("@TotalVMI", _TotalVMI);
            _spList.Add("@TotalCMI", _TotalCMI);
            _spList.Add("@PaymentType", PaymentType);
            _spList.Add("@Step", 1);

            object _retObjectUserIdUpdate = _dbUpdate.ExecuteSP(_spName, _spList);
            Update = Convert.ToInt64(_retObjectUserIdUpdate);
            return Update;
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

    private bool NotificationEmail(string carresultid, string Email, string Name, string Mobile)
    {
        string qs_carselected = carresultid;
        string _makemodel = "";
        string _garagetype = "";
        string _caryear = "";
        string _ncb = "";
        string _policystartdate = "";

        Int64 _cecarid = 0;

        if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
        {
            _cecarid = Convert.ToInt64(Session[General.CarId]);
            Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }

            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

            if (_cardetail != null)
            {
                if (_cardetail.MakeModelDesc != null && _cardetail.MakeModelDesc != "")
                    _makemodel = _cardetail.MakeModelDesc;
                else
                    _makemodel = _cardetail.CarModelName + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                _caryear = _cardetail.ManufactYear.ToString();
            }

            if (_carpolicy != null)
            {
                if (_carpolicy.GarageType.ToString().Trim() == "1")
                    _garagetype = Resources.CarInsurance.Garage_Authorized;
                else
                    _garagetype = Resources.CarInsurance.Garage_Dealer;

                _ncb = _carpolicy.NCDPercent.ToString();
                _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
            }
        }

        string _refno = "";
        string _companyName = "";
        //string _insurerimageurl = "";
        string _package = "";
        string _annualprice = "";


        if (qs_carselected != "" && Session[General.UserId] != null && Session[General.CarId] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);



                string CITempResultId = qs_carselected;

                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            _refno = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());

                            if (dtFiltered.Rows[iRows]["packagename"].ToString() != "GluayGluay.com Special")
                            {
                                if (Session["Language"] != null)
                                {
                                    if (Session["Language"].ToString() == "th-TH")
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "1");
                                    else
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }
                                else
                                {
                                    //english
                                    _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }

                                //_insurerimageurl = "http://www.gluaygluay.com/" + CE.Global.General.GetProviderCompanyLogo(_providercompanyid);
                            }
                            else
                            {
                                _companyName = "";

                                //_insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + "/images/public/logo/gluaygluay_logo.png";
                            }

                            _package = "<strong>" + dtFiltered.Rows[iRows]["packagename"].ToString() + "</strong>";


                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"]) != Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"]))
                            {
                                _annualprice = "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString())) + "</s>";
                            }

                            _annualprice = _annualprice + "<div style='color:#F00;font-size:20px;font-weight:bold;' >";
                            _annualprice = _annualprice + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"].ToString())); //"999.00";
                            _annualprice = _annualprice + "</div>";
                        }
                    }
                }
            }
        }
        string _emailList = "", _ccemailList = "", _bccemailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
        _emailList = System.Configuration.ConfigurationSettings.AppSettings["Mobile.GGSupport"].ToString();
        _title = "";

        _title = "gluaygluay.com Mobile Customer Proposal (Ref No : " + _refno + ")";

        _message.Append("<table cellpadding='0' cellspacing='0' border='0' width='500' style='font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0 auto;'>");
        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'>");
        _message.Append("<strong>Mobile Customer Proposal Details</strong></td></tr>");
        _message.Append("<tr><td>&nbsp;</td></tr>");
        _message.Append("<tr><td>&nbsp;</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><br /><table cellspacing='0' cellpadding='2' width='100%' border='0'>");

        //_message.Append("<tr><td valign='top'>QuoteRefNo</td>");
        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.Name + "</td>");
        _message.Append("<td valign='top'><strong><u>" + Name + "</u></strong></td></tr>");

        //_message.Append("<tr><td valign='top'>QuoteRefNo</td>");
        _message.Append("<tr><td valign='top'>" + Resources.CarInsurance.EmailAddress + "</td>");
        _message.Append("<td valign='top'><strong><u>" + Email + "</u></strong></td></tr>");

        //_message.Append("<tr><td valign='top'>QuoteRefNo</td>");
        _message.Append("<tr><td valign='top'>" + Resources.CarMenu.Mobile + "</td>");
        _message.Append("<td valign='top'><strong><u>" + Mobile + "</u></strong></td></tr>");

        //_message.Append("<tr><td valign='top'>QuoteRefNo</td>");
        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.QuoteReferenceNumber + "</td>");
        _message.Append("<td valign='top'><strong><u>" + _refno + "</u></strong></td></tr>");

        //_message.Append("<tr><td width='50%' valign='top'>GarageType</td>");
        _message.Append("<tr><td width='50%' valign='top'> " + Resources.ProposalForm.GarageType + " </td>");
        _message.Append("<td width='50%' valign='top'><strong>" + _garagetype + "</strong></td></tr>");

        //_message.Append("<tr><td valign='top'>CarMakeModel</td>");
        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.CarMakeModel + "</td>");
        _message.Append("<td valign='top'><strong>" + _makemodel + "</strong></td></tr>");

        //_message.Append("<tr><td valign='top'>CarModelYear</td>");
        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.CarModelYear + "</td>");
        _message.Append("<td valign='top'><strong>" + _caryear + "</strong></td></tr>");

        ////_message.Append("<tr><td valign='top'>Cover Commencement Date</td>");
        //_message.Append("<tr><td valign='top'>" + Resources.ProposalForm.CoverCommencementDate + "</td>");
        //_message.Append("<td valign='top'><strong>" + _policystartdate + "</strong></td></tr>");

        ////_message.Append("<tr><td valign='top'>NCB</td>");
        //_message.Append("<tr><td valign='top'>" + Resources.ProposalForm.NCB + "</td>");
        //_message.Append("<td valign='top'><strong>" + _ncb + "</strong></td></tr>");

        if (_companyName.Trim() != "")
        {
            //_message.Append("<tr><td valign='top'>Insurer</td>");
            _message.Append("<tr><td valign='top'>" + Resources.CarInsuranceResultPage.Insurer + "</td>");
            _message.Append("<td valign='top'><strong>" + _companyName + "</strong></td></tr>");

        }

        _message.Append("</table><br /></td></tr></table>");


        if (MyMailManager.SendNotificationtoAgent(_emailList, _ccemailList, _bccemailList, _title, _message.ToString()))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

    private bool SendProposalToUserNEW(string CITempResultId, Int64 ProviderCompanyId)
    {
        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        CE.User.Profile usrprofile = new Profile();
        ProfileDB usrprofiledb = new ProfileDB();

        usrprofile = usrprofiledb.GetProfile(Convert.ToInt64(Session[General.UserId].ToString()));

        string userfirstname = "";

        if (usrprofile != null)
        {
            userfirstname = usrprofile.FirstName;
        }

        string _refNo = "";
        CarDetailTH _cardetailth = new CarDetailTH();
        CarDetailTHDB _cardetailthdb = new CarDetailTHDB();
        CE.Database.MyDatabase _db = new CE.Database.MyDatabase();
        DataSet _dsInsurance = new DataSet();

        string _Premium = "";
        string _InsuranceType = "";
        string _NCB = "";

        string _GarageType = "";
        string _CarYear = "";
        string _CarMakeModel = "";
        string _CarType = "";
        string _CarPlate = "";
        string _NameDriver = "";
        string _Name = "";
        string _isCTPL = "No";
        string _CTPL = "";
        string _PolicyStartDate = "";

        Int64 _companyId = 0;

        MyDatabase _dbSI = new MyDatabase();
        SortedList _spListSI = new SortedList();
        _spListSI.Add("@CarId", _carId);
        _spListSI.Add("@CarResultId", Convert.ToInt64(CITempResultId));
        _dsInsurance = _dbSI.GetDataSet("sprocCarInsuranceMobileCompletedItem", _spListSI);
        if (_dsInsurance != null && _dsInsurance.Tables[0].Rows.Count > 0)
        {
            switch (_dsInsurance.Tables[0].Rows[0]["InsuranceType"].ToString())
            {
                case "Class 1":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOne;
                    _NCB = _dsInsurance.Tables[0].Rows[0]["NCB"].ToString();
                    break;
                case "Class 1 (Low Cost)":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOneLowCost;
                    _NCB = "N/A";
                    break;
                case "Class 2+":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassTwoPlus;
                    _NCB = "N/A";
                    break;
                case "Class 3+":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThreePlus;
                    _NCB = "N/A";
                    break;
                case "Class 3":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThree;
                    _NCB = "N/A";
                    break;
            }



            _GarageType = _dsInsurance.Tables[0].Rows[0]["GarageType"].ToString() == "Authorized" ? Resources.CarInsurance.Garage_Authorized : Resources.CarInsurance.Garage_Dealer;
            _CarYear = _dsInsurance.Tables[0].Rows[0]["CarModelYear"].ToString();
            _CarMakeModel = _dsInsurance.Tables[0].Rows[0]["MakeModelDesc"].ToString();
            _CarType = _dsInsurance.Tables[0].Rows[0]["VehicleType"].ToString() == "Private Use" ? Resources.CarInsurance.VehicleType_Private : Resources.CarInsurance.VehicleType_Commercial;
            _NameDriver = _dsInsurance.Tables[0].Rows[0]["Driver"].ToString() == "Yes" ? Resources.CarInsurance.Option_YesSpecify : Resources.CarInsurance.Option_NoSpecify;

            _isCTPL = "No";
            _CTPL = "0";
            if (_dsInsurance.Tables[1].Rows.Count > 0)
            {
                string CarId = Session[General.CarId].ToString();
                _Name = _dsInsurance.Tables[1].Rows[0]["Name"].ToString();
                _refNo = General.GetReferenceNumber(CarId.ToString(), ProviderCompanyId.ToString(), "");
            }

            _CarMakeModel = _CarMakeModel.Replace("_", " ");
        }

        bool _retVal = false;
        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.IsCXLive");

        string _emailTo = Session[General.UserEmail].ToString();
        string _customername = _Name; // Session[General.UserName].ToString();
        string _emailSubject = "<mobile> - " + Resources.EmailMessage.Subject; // "Your Car Insurance Quotes on CompareXpress(Thailand)";
        string _mailBody = "";

        string domainUrl = "";
        Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

        domainUrl = "http://www.gluaygluay.com/mobile";
        if (_strCXLive == "0")
        {
            domainUrl = "http://test.gluaygluay.com.gluaygluay.info/mobile";
        }

        string imgLogoUrl = domainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.TH.LogoPath");

        #region "Mail Body"

        #region Header
        _mailBody = "<html>";
        _mailBody += "<head>";
        _mailBody += "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";
        _mailBody += "<title>GluayGluay</title>";
        _mailBody += "<style>";

        _mailBody += ".body {";
        _mailBody += "margin-left: 0px;";
        _mailBody += "margin-top: 0px;";
        _mailBody += "margin-right: 0px;";
        _mailBody += "margin-bottom: 0px;";
        _mailBody += "font-family: Arial, sans-serif;";
        _mailBody += "font-size: 14px;";
        _mailBody += "color: #000000;";
        _mailBody += "background-repeat: repeat-x;";
        _mailBody += "background-color: #fff;";
        _mailBody += "text-decoration: none;}";

        _mailBody += "</style>";
        _mailBody += "</head>";
        #endregion

        _mailBody += "<body class='body'>";
        _mailBody += "<table width='800' border='0' align='center' cellpadding='0' cellspacing='0' style='font-size:14px;'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='1474' valign='top'>";
        _mailBody += "<table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td><span class='email-banner'><img src='" + domainUrl + "/images/email-header.jpg' width='800' height='100' alt='' /></span></td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";

        #region Thank you
        _mailBody += "<table width='329' border='0' cellspacing='0' cellpadding='0' style='line-height:20px;'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='329'><strong>" + Resources.Proposal.OrderConfirmation + "</strong></td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += " <td>" + Resources.Proposal.ThankYou + "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion

        #region Car Details
        _mailBody += "<table width='700' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='146' valign='top' bgcolor='#C1C1C1'>";
        _mailBody += "<br />";
        _mailBody += "<table width='800' border='0' cellspacing='1' cellpadding='1'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='26' colspan='4' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; font-weight: bold; padding-left: 10px; padding-bottom: 5px;";
        _mailBody += "padding-top: 5px;'>" + Resources.Proposal.OrderNo + " " + _refNo + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td width='150' height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.NameLastname + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='363' height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _Name + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='148' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.OrderDate + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='126' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += General.GetUTCDateTime().ToString("dd/MMM/yyyy") + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.CarYear + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _CarYear + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.NamedDrivers + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _NameDriver + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.MakeModel + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='30' colspan='3' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _CarMakeModel + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.GarageType + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _GarageType + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.NCB + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _NCB + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion

        //Sakthi on 18 Jan 2012 -- Start
        DataSet _dsResults = new DataSet();
        DataView dvResults = new DataView();
        SortedList _sPara = new SortedList();

        _sPara.Add("@CarId", Convert.ToInt64(Session[General.CarId].ToString()));
        _sPara.Add("@RefUserId", Convert.ToInt64(Session[General.UserId].ToString()));
        _dsResults = _db.GetDataSet("sprocCarInsuranceResultSelectItemList", _sPara);
        if (_dsResults.Tables.Count > 0 && _dsResults.Tables[0].Rows.Count > 0)
        {
            dvResults = _dsResults.Tables[0].DefaultView;
            dvResults.RowFilter = " CITempResultId in (" + CITempResultId + ")";
        }
        //Sakthi on 18 Jan 2012 -- End

        dvResults.RowFilter = " CITempResultId in (" + CITempResultId + ")";

        DataTable dtResults = dvResults.ToTable();

        bool IsGGSpecial = false;
        if (dtResults.Rows.Count > 0)
        {
            string _providercompanyid = dtResults.Rows[0]["providercompanyid"].ToString();
            //logo
            string logourl = "";
            string package = dtResults.Rows[0]["PackageName"].ToString();
            if (dtResults.Rows[0]["PackageName"].ToString() != "GluayGluay.com Special")
            {
                logourl = domainUrl + CE.Global.General.GetProviderCompanyLogo(_providercompanyid);
            }
            else
            {
                //[Yui] @13/09/2013
                IsGGSpecial = true;
                // --- End ---

                logourl = domainUrl + "/images/gg-logo/gluaygluay-logo.png";
                package += " (" + Resources.CarInsuranceResultPage.SpecialNCB + ")";
            }

            #region Main body

            #region Not Using
            float _fMonthlyPremiumAmount = Convert.ToSingle(dtResults.Rows[0]["MonthlyPremiumAmount"].ToString());
            string monthlyInstallment = "";

            if (_fMonthlyPremiumAmount > 0.0f)
            {
                string _monthlyPremiumAmount = String.Format("{0:0,0.00}", _fMonthlyPremiumAmount);
                monthlyInstallment = _monthlyPremiumAmount + "/mth<br/>";
            }
            else
            {
                monthlyInstallment = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
            }
            #endregion

            _mailBody += "<table width='800' border='0' cellspacing='0' cellpadding='0'>";
            _mailBody += "<tr>";
            _mailBody += "<td height='129' valign='top'>";
            _mailBody += "<table width='520' border='0' cellspacing='1' cellpadding='1' bgcolor='#C1C1C1'>";

            #region Provider Logo & Package name
            _mailBody += "<tr>";
            _mailBody += "<td height='25' colspan='2' bgcolor='#FFFFFF' align='center'>";
            _mailBody += "<span style='padding: 10px;'>";
            _mailBody += "<img src='" + logourl + "' alt='' /></span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td width='324' height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.ProposalForm.Package + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td width='193' height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += package + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region Deductible
            float _fDEC = 0.0f;// Convert.ToSingle(dtResults.Rows[0]["DEC"].ToString());
            if (!float.TryParse(dtResults.Rows[0]["DEC"].ToString().Replace(",", ""), out _fDEC))
            {
                _fDEC = 0.0f;
            }
            string deductible = "";
            if (_fDEC > 0.0f)
            {
                deductible = String.Format("{0:0,0.00}", _fDEC);
            }
            else
            {
                deductible = Resources.CarInsuranceResultPage.Waived;
            }
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.DEC + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += deductible + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region Own Damage
            string suminsured = "0";// String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["SumInsured"].ToString()));
            float _flsuminsured = 0.0f;
            if (!float.TryParse(dtResults.Rows[0]["SumInsured"].ToString().Replace(",", ""), out _flsuminsured))
            {
                _flsuminsured = 0.0f;
            }
            suminsured = String.Format("{0:#,0}", _flsuminsured);
            if (_flsuminsured == 0)
            {
                suminsured = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.OwnDamage + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += suminsured + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region Fire
            string fire = "0"; // String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["Fire"].ToString()));
            float _flfire = 0.0f;
            if (!float.TryParse(dtResults.Rows[0]["Fire"].ToString().Replace(",", ""), out _flfire))
            {
                _flfire = 0.0f;
            }
            fire = String.Format("{0:#,0}", _flfire);
            if (_flfire == 0)
            {
                fire = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.Fire + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += fire + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region Theft
            string theft = "0";// String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["Theft"].ToString()));
            float _fltheft = 0.0f;
            if (!float.TryParse(dtResults.Rows[0]["Theft"].ToString().Replace(",", ""), out _fltheft))
            {
                _fltheft = 0.0f;
            }
            theft = String.Format("{0:#,0}", _fltheft);
            if (_fltheft == 0)
            {
                theft = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.Theft + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += theft + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region TPPD
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.TPPD + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["TPPD"].ToString())) + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region TPBIA
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.TPBIA + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["TPBIA"].ToString())) + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region TPBIP
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.TPBIP + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["TPBIP"].ToString())) + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region PA Driver
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.PADriver + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["PADriver"].ToString())) + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region Medical Expense
            int _MedicalExpense = 0;// Convert.ToInt32(dtResults.Rows[0]["MedicalExpense"].ToString());
            if (int.TryParse(dtResults.Rows[0]["MedicalExpense"].ToString().Replace(",", ""), out _MedicalExpense))
            {
                _MedicalExpense = 0;
            }
            string medicalExpense = "";
            if (_MedicalExpense == 0)
            {
                medicalExpense = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
            }
            else
            {
                medicalExpense = String.Format("{0:#,0}", Convert.ToSingle(_MedicalExpense.ToString()));
            }
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.MED + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += medicalExpense + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region Bail Bond
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.BailBond + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
            _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:#,0}", Convert.ToSingle(dtResults.Rows[0]["BailBond"].ToString())) + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            #region CTPL
            if (_isCTPL == "Yes")
            {
                //premium before ctpl
                _mailBody += "<tr>";
                _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
                _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
                _mailBody += Resources.CarInsuranceResultPage.AnnualPremium + "</span>";
                _mailBody += "</td>";
                _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";

                double BeforeCTPL = Convert.ToSingle(_Premium) - Convert.ToSingle(_CTPL);
                if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
                {
                    _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
                    _mailBody += "<s>"+ String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + " " + Resources.CarInsurance.Baht + "</s></span><br />";
                }

                _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
                _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(BeforeCTPL)) + " " + Resources.CarInsurance.Baht + "</span>";
                _mailBody += "</td>";
                _mailBody += "</tr>";


                //CTPL Amount
                _mailBody += "<tr>";
                _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
                _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
                _mailBody += Resources.Proposal.CTPL + "</span>";
                _mailBody += "</td>";
                _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
                _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
                _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_CTPL)) + " " + Resources.CarInsurance.Baht + "</span>";
                _mailBody += "</td>";
                _mailBody += "</tr>";
            }
            #endregion

            #region Premium (+taxes & duties)
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.TotalVMI + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";

            //Sakthi on 10 Nov 2014 - Start
            if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
            {
                _mailBody += "<span style='font-size: 16px; text-decoration: line-through; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
                _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + " " + Resources.CarInsurance.Baht + "</span><br />";
            }
            _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"].ToString())) + " " + Resources.CarInsurance.Baht + "</span>";
            //if (_isCTPL == "No")
            //{
            //    if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
            //    {
            //        _mailBody += "<span style='font-size: 16px; text-decoration: line-through; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            //        _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + "</span><br />";
            //    }
            //    _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            //    _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"].ToString())) + "</span>";
            //}
            //else
            //{
            //    _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            //    _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_Premium)) + "</span>";
            //}
            //Sakthi on 10 Nov 2014 - End
            _mailBody += "</td>";
            _mailBody += "</tr>";
            #endregion

            _mailBody += "</table>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";
            _mailBody += "<br />";
            #endregion
        }

        _mailBody += "<table width='800' border='0' cellspacing='0' cellpadding='0' style='line-height:20px;'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='787' height='26' colspan='4' bgcolor='#FFFFFF'>";

        #region BankIn Message
        _mailBody += "<strong><u>" + Resources.Proposal.ForBankIn + "</u></strong>";
        _mailBody += "<br />";
        _mailBody += Resources.Proposal.ForBankInMsg1;
        _mailBody += " ";
        _mailBody += Resources.Proposal.LineQrScan;
        _mailBody += "<br/><div style=\"text-align:center; width:400px\">";
        _mailBody += "<img runat=\"server\" id=\"imgSpecial\" alt=\"Line QR\" src=\"" + domainUrl + "/images/line-qr.jpg\" /></div>";

        _mailBody += "<br />";
        _mailBody += Resources.Proposal.ForBankInMsg2;
        _mailBody += "<br />";
        #endregion

        #region Remarks
        _mailBody += "<p>";
        _mailBody += "<strong>" + Resources.Proposal.Remarks + "</strong>";
        //[Yui] @13/09/2013
        if (!IsGGSpecial)
        {
            _mailBody += "<br/>" + Resources.Proposal.RemarksMsg1;
        }
        else
        {
            _mailBody += "<br/>" + Resources.Proposal.RemarksMsgGGSpecial;
        }
        _mailBody += "</p>";
        _mailBody += "<hr />";

        _mailBody += Resources.EmailMessage.FooterRisk;
        //_mailBody += "This Quote is subject to the insurer's final confirmation and coverage is only effective";
        //_mailBody += "when the";
        //_mailBody += "<br />";
        //_mailBody += "insurer has accepted the risk.";
        #endregion

        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<hr />";

        #region Footer

        _mailBody += "<table width='800' border='0' cellspacing='0' cellpadding='0' style='line-height:20px;'>";
        _mailBody += "<tr>";
        _mailBody += "<td colspan='2' valign='top'>";
        _mailBody += "<strong>" + Resources.WelcomeEmail.CompanyAdd1 + "</strong><br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd2 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd3 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd4 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyPhone + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyFax + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyEmail + "<br />";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";

        _mailBody += "<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='https://www.facebook.com/GGmotor' target='_blank'><img src='" + domainUrl + "/images/icons/fb-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='https://plus.google.com/+Gluaygluay/posts' target='_blank'><img src='" + domainUrl + "/images/icons/g-plus-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='http://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA' target='_blank'><img src='" + domainUrl + "/images/icons/youtube-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='http://iconosquare.com/ggmotor' target='_blank'><img src='" + domainUrl + "/images/icons/instagram-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='43' style='text-align: center'>";
        _mailBody += "<a href='http://www.linkedin.com/company/-com-gluaygluay-com-' target='_blank'><img src='" + domainUrl + "/images/icons/linkedin-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";

        _mailBody += "<hr />";
        _mailBody += "<table style='line-height:20px;' width='800' border='0' cellspacing='0' cellpadding='0' background='" + domainUrl + "/images/email-footer.jpg'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='49'><br><p style='text-align: center'>© 2014 gluaygluay.com. All rights reserved.<br>";
        _mailBody += Resources.EmailMessage.AutoEmail + "</p></td>";
        _mailBody += "</tr>";
        _mailBody += "</table></td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "</body>";
        _mailBody += "</html>";
        #endregion

        #endregion

        if (MyMailManager.SendSelectedCARMessage(_emailTo, _emailSubject + " (Ref No : " + _refNo + ") ", _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    private bool SendCounterServiceNotification()
    {
        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        CE.User.Profile usrprofile = new Profile();
        ProfileDB usrprofiledb = new ProfileDB();

        usrprofile = usrprofiledb.GetProfile(Convert.ToInt64(Session[General.UserId].ToString()));

        string userfirstname = "";

        if (usrprofile != null)
        {
            userfirstname = usrprofile.FirstName;
        }

        string _refNo = "";
        CarDetailTH _cardetailth = new CarDetailTH();
        CarDetailTHDB _cardetailthdb = new CarDetailTHDB();
        CE.Database.MyDatabase _db = new CE.Database.MyDatabase();
        DataSet _dsInsurance = new DataSet();

        string _Premium = "";
        string _Gender = "";
        string _DOB = "";
        string _Occupation = "";
        string _InsuranceType = "";
        string _NCB = "";

        string _GarageType = "";
        string _CarYear = "";
        string _CarMakeModel = "";
        string _CarType = "";
        string _CarPlate = "";
        string _NameDriver = "";
        string _Name = "";
        string _PolicyStartDate = "";
        string _isCTPL = "No";
        string _CTPL = "";

        Int64 _companyId = 0;

        System.Data.DataTable _dtSeletectItem = new System.Data.DataTable("SelectedResultItem");
        _dtSeletectItem = _db.GetDataTable("Select * from tblCarInsuranceSelectItemTH WHERE CarId = " + _carId.ToString());
        if (_dtSeletectItem != null && _dtSeletectItem.Rows.Count > 0)
        {
            _companyId = Convert.ToInt64(_dtSeletectItem.Rows[0]["ProviderCompanyId"].ToString());
            _Premium = Convert.ToSingle(_dtSeletectItem.Rows[0]["AnnualPremium"].ToString()).ToString("#.00");
        }
        CarInsuranceCompletedItemDB _carinsurancecompleteditemdb = new CarInsuranceCompletedItemDB();
        _dsInsurance = _carinsurancecompleteditemdb.GetCarInsuranceCompletedItem(_carId, _companyId);
        if (_dsInsurance != null && _dsInsurance.Tables[0].Rows.Count > 0)
        {
            _Gender = _dsInsurance.Tables[0].Rows[0]["Gender"].ToString() == "Male" ? Resources.CarInsurance.Male : Resources.CarInsurance.Female;
            _DOB = Convert.ToDateTime(_dsInsurance.Tables[0].Rows[0]["DOB"]).ToString("dd-MMM-yyyy");
            if (CE.Global.General.SetCulture() == "th-TH")
            {
                _Occupation = _dsInsurance.Tables[0].Rows[0]["THOccupation"].ToString();
            }
            else
            {
                _Occupation = _dsInsurance.Tables[0].Rows[0]["ENOccupation"].ToString();
            }
            switch (_dsInsurance.Tables[0].Rows[0]["InsuranceType"].ToString())
            {
                case "Class 1":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOne;
                    _NCB = _dsInsurance.Tables[0].Rows[0]["NCB"].ToString();
                    break;
                case "Class 1 (Low Cost)":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOneLowCost;
                    _NCB = "N/A";
                    break;
                case "Class 2+":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassTwoPlus;
                    _NCB = "N/A";
                    break;
                case "Class 3+":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThreePlus;
                    _NCB = "N/A";
                    break;
                case "Class 3":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThree;
                    _NCB = "N/A";
                    break;
            }

            _GarageType = _dsInsurance.Tables[0].Rows[0]["GarageType"].ToString() == "Authorized" ? Resources.CarInsurance.Garage_Authorized : Resources.CarInsurance.Garage_Dealer;
            _CarYear = _dsInsurance.Tables[0].Rows[0]["CarModelYear"].ToString();
            _CarMakeModel = _dsInsurance.Tables[0].Rows[0]["MakeModelDesc"].ToString();
            _CarType = _dsInsurance.Tables[0].Rows[0]["VehicleType"].ToString() == "Private Use" ? Resources.CarInsurance.VehicleType_Private : Resources.CarInsurance.VehicleType_Commercial;
            _NameDriver = _dsInsurance.Tables[0].Rows[0]["Driver"].ToString() == "Yes" ? Resources.CarInsurance.Option_YesSpecify : Resources.CarInsurance.Option_NoSpecify;

            if (_dsInsurance.Tables[1].Rows.Count > 0)
            {
                _CarPlate = _dsInsurance.Tables[1].Rows[0]["VehicleNo"].ToString();
                if (_dsInsurance.Tables[1].Rows[0]["PolicyStartDate"] != DBNull.Value)
                {
                    _PolicyStartDate = Convert.ToDateTime(_dsInsurance.Tables[1].Rows[0]["PolicyStartDate"]).ToString("dd-MMM-yyyy");
                }
                _Name = _dsInsurance.Tables[1].Rows[0]["Name"].ToString();
                _refNo = _dsInsurance.Tables[1].Rows[0]["QuoteRefNo"].ToString();

                _isCTPL = _dsInsurance.Tables[1].Rows[0]["CTPL"].ToString();
                _CTPL = _dsInsurance.Tables[1].Rows[0]["CTPLAmount"].ToString();
            }
        }

        bool _retVal = false;
        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive");
        string _isOnline = "Online";
        if (_strCXLive == "0")
            _isOnline = "Test";

        string _emailTo = System.Configuration.ConfigurationSettings.AppSettings["TH.CI_ADM_TO"].ToString();
        string _emailCC = "";
        string _emailBCC = "";
        string _customername = Session[General.UserName].ToString();
        string _emailSubject = "";
        //if (rdoSevenEleven.Checked)
        //{
        //    _emailSubject = "<" + _isOnline + "> - " + Resources.Proposal.PendingPayment + " 7/11 - " + Resources.EmailMessage.AZCPSubject;
        //}
        //else if (rdoTesco.Checked)
        //{
        //    _emailSubject = "<" + _isOnline + "> - " + Resources.Proposal.PendingPayment + " Tesco - " + Resources.EmailMessage.AZCPSubject;
        //}
        //else if (rdoTrueMoney.Checked)
        //{
        //    _emailSubject = "<" + _isOnline + "> - " + Resources.Proposal.PendingPayment + " True Money - " + Resources.EmailMessage.AZCPSubject;
        //}

        string _mailBody = "";

        _mailBody = "<body class='email_body'>";
        _mailBody += "<style type='text/css'>";
        _mailBody += ".email_body {background: white;margin: 0;padding: 0;color: #4c4c4c;font-family: Arial, Helvetica, sans-serif;font-size: 0.85em;}";
        _mailBody += "a {text-decoration:underline;color:#2c95cc;} ";
        _mailBody += "#email_container {margin:0 auto;padding:20px;width:600px; height:auto;} ";
        _mailBody += "#email_body {width:100%; text-align: left !important;} ";
        _mailBody += ".email_pad10px {padding:10px;} ";
        _mailBody += ".email_results td {width:33%;} ";
        _mailBody += "</style>";
        _mailBody += "<center> <br /><br />";

        _mailBody += "<table cellpadding='0' cellspacing='0' border='0' width='570'>";
        _mailBody += "<tr><td width='570'><table cellspacing='0' cellpadding='0' width='100%' border='0'>";
        _mailBody += "<tr><td width='50%' valign='top'><strong>" + Resources.Proposal.PendingPayment + "</strong><br /><br />";
        _mailBody += Resources.Proposal.AgentMessage + "<br/><br/>";
        _mailBody += "<br/><strong>" + Resources.Proposal.OrderNo + " </strong>" + _refNo + "</td><td width='50%' align='right' valign='top'></td></tr>";
        _mailBody += "</table>";

        _mailBody += "<table cellspacing='0' cellpadding='2' width='570' border='0'>";
        _mailBody += "<tr><td width='50%' valign='top'>" + Resources.Proposal.InsuranceType + " " + _InsuranceType + "</td><td width='50%;' valign='top'>Car Id.: " + Session[General.CarId].ToString() + "</td>";
        _mailBody += "</tr><tr><td valign='top'>" + Resources.Proposal.RefNo + ": " + _refNo + "</td><td valign='top'>" + Resources.Proposal.OrderDate + ": " + General.GetUTCDateTime().ToString("dd/MMM/yyyy") + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.MakeModel + ": " + _CarMakeModel + "</td><td valign='top'>" + Resources.Proposal.CarYear + ": " + _CarYear + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.GarageType + ": " + _GarageType + "</td><td valign='top'>" + Resources.Proposal.NamedDrivers + ": " + _NameDriver + "</td></tr>";
        _mailBody += "<tr><td valign='top'>" + Resources.Proposal.NameLastname + ": " + _Name + " </td><td valign='top'>" + Resources.Proposal.NCB + ": " + _NCB + "</td></tr>";
        _mailBody += "</table> <br /><br />";
        _mailBody += "</td></tr>";
        _mailBody += "<tr><td id='email_footer'>";
        _mailBody += "</td></tr></table>";
        _mailBody += "</center></body>";

        if (MyMailManager.SendSelectedCARMessageToAgent(_emailTo, _emailCC, _emailBCC, _emailSubject + " (Ref No : " + _refNo + ") ", _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    public bool ValidDate(Int32 Year, Int32 Month, Int32 Day)
    {
        bool _isValid = true;
        int daysInMonth = 0;
        string leap, monthValid, dayValid, yearValid;
        if (Year >= 0000)
        {
            yearValid = "yes";
        }
        else
        {
            yearValid = "no";
        }
        if (Year % 400 == 0)
        {
            leap = "yes";
        }
        else if (Year % 100 == 0)
        {
            leap = "no";
        }
        else if (Year % 4 == 0)
        {
            leap = "yes";
        }
        else
        {
            leap = "no";
        }

        switch (Month)
        {
            case 1: daysInMonth = 31;
                break;
            case 3: daysInMonth = 31;
                break;
            case 4: daysInMonth = 30;
                break;
            case 5: daysInMonth = 31;
                break;
            case 6: daysInMonth = 30;
                break;
            case 7: daysInMonth = 31;
                break;
            case 8: daysInMonth = 31;
                break;
            case 9: daysInMonth = 30;
                break;
            case 10: daysInMonth = 31;
                break;
            case 11: daysInMonth = 30;
                break;
            case 12: daysInMonth = 31;
                break;
        }

        if (Month >= 1 && Month <= 12)
        {
            monthValid = "yes";
        }
        else
        {
            monthValid = "no";
        }
        if (Month == 2)
        {
            if (leap == "no")
            {
                daysInMonth = 28;
            }
            else if (leap == "yes")
            {
                daysInMonth = 29;
            }
        }

        if (1 <= Day && Day <= daysInMonth)
        {
            dayValid = "yes";
        }

        else
        {
            dayValid = "no";
        }

        if ((dayValid == "yes") && (monthValid == "yes") && (yearValid == "yes"))
        {
            _isValid = true;
        }
        else
        {
            _isValid = false;
        }

        return _isValid;
    }

    private string EmailAddress
    {
        get { return txtUserEmail.Text.Trim(); }
    }

    private string MobileNumber
    {
        get { return txtUserMobile.Text.Trim(); }
    }

    private string Name
    {
        get { return txtUserName.Text.Trim(); }
    }

    private void SetCookies()
    {
        try
        {
            string _isAccept = "FALSE";
            if (hdnIsAceept.Value == "TRUE")
            {
                _isAccept = "TRUE";
            }
            HttpCookie _cookie = new HttpCookie("GGMobileQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(txtUserName.Text, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(txtUserEmail.Text, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(txtUserMobile.Text, true));
            _cookie.Values.Add("IsAccept", MySecurity.Encrypt(_isAccept, true));
            _cookie.Expires = DateTime.Now.AddDays(90);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void GetCookies()
    {
        try
        {
            HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
            if (_cookie != null)
            {
                txtUserName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtUserEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                string _mobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                txtUserMobile.Text = _mobile;
                string _isaccept = "FALSE";
                string[] _CK = _cookie.Value.Split('&');
                if (_CK.Length > 3)
                {
                    _isaccept = MySecurity.Decrypt(_cookie.Values.Get("IsAccept"), true);
                    if (_isaccept != null && _isaccept == "TRUE")
                    {
                        hdnIsAceept.Value = "TRUE";
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    #region Change Email - create new account

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                _profile.FirstName = HttpUtility.HtmlEncode(txtUserName.Text);
                _profile.SurName = "";
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M';
                }
                _profile.Status = "Complete";
                _profile.IsAcceptTC = true; //chkAggrement.Checked;

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtUserMobile.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }
        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), 400);
            if (_useraccount != null)
            {
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                }
            }
            else
            {

                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtUserEmail.Text.Trim().ToLower();
                string _authcode = txtUserMobile.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDMOBILECI";
                _useraccount.UserTypeId = 400;
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtUserName.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = 140;
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = true;// chkAggrement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtUserMobile.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    private void UpdateUserIdCarDetails(Int64 CarId, Int64 UserId, Int64 ExistingUserId, string ExistingEmail, string ChangeStatus, string Email, string Name, string Mobile)
    {
        try
        {
            Int64 _result = -1;
            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();
            string _spName = "sprocCarDetailUpdateSingleItemByUserId";
            SortedList _sPara = new SortedList();
            _sPara.Add("@CarId", CarId);
            _sPara.Add("@RefCEUserId", UserId);
            _sPara.Add("@ExistingUserId", ExistingUserId);
            _sPara.Add("@ExistingEmail", ExistingEmail);
            _sPara.Add("@ChangeStatus", ChangeStatus);
            _sPara.Add("@Email", Email);
            _sPara.Add("@Name", Name);
            _sPara.Add("@Mobile", Mobile);

            _result = _db.ExecuteNonSqlSP(_spName, _sPara);
        }
        catch (Exception ex)
        {
        }
    }

    #endregion

}
